<template>
  <el-dialog
    v-model="visible"
    :title="!isShowProd ? $t('product.select') : $t('prodList.lookOver')"
    :close-on-click-modal="false"
    :before-close="beforeClose"
    top="50px"
    style="min-width: 900px;"
  >
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"
      @submit.prevent
    >
      <el-form-item :label="$t('product.prodName')">
        <el-input
          v-model="prodName"
          :placeholder="$t('product.prodName')"
          maxlength="50"
          clearable
          style="width: 200px;"
        />
      </el-form-item>
      <el-form-item :label="$t('marketing.subHeadings')">
        <!-- expand-trigger="hover" -->
        <el-cascader
          v-model="selectedCategory"
          :props="categoryTreeProps"
          :options="categoryList"
          :clearable="true"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{ $t('order.query') }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="clean"
        >
          {{ $t('temp.setNull') }}
        </div>
      </el-form-item>
    </el-form>
    <div class="main-container distribution-prod-add-or-update">
      <div class="table-con">
        <el-table
          ref="prodTableRef"
          v-loading="dataListLoading"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          :data="dataList"
          style="width: 100%"
          height="450"
        >
          <el-table-column
            v-if="!isShowProd"
            width="50"
            header-align="center"
            align="center"
          >
            <template #default="scope">
              <div>
                <el-radio
                  v-model="prodId"
                  :label="scope.row.prodId"
                  @change="getSelectProdRow(scope.$index, scope.row)"
                >
&nbsp;
                </el-radio>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="prodName"
            align="left"
            :label="$t('product.prodName')"
          >
            <template #default="scope">
              <div class="table-cell-text">
                {{ scope.row.prodName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            width="140"
            :label="$t('product.pic')"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <ImgShow
                  :key="scope.row.prodId"
                  height="60px"
                  width="100%"
                  :src="scope.row.pic"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            align="center"
            :label="$t('product.price')"
          />
        </el-table>
      </div>
    </div>
    <el-pagination
      :current-page="page.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="page.pageSize"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
      @update:page-size="onPageSizeChange"
      @update:current-page="onPageChange"
    />
    <template #footer>
      <div
        class="default-btn primary-btn"
        @click="selectProd()"
      >
        {{ $t('crud.filter.submitBtn') }}
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate, idList } from '@/utils/index.js'

const emit = defineEmits(['refreshDiscountProds'])

const visible = ref(false)
const dataForm = reactive({
  product: ''
})
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const prodName = ref('')
const isShowProd = ref(0)
const prodId = ref(0)
const discountProds = ref([])
const discountId = ref(0)
const dataList = ref([])
const dataListLoading = ref(false)
const dataListSelections = ref([])
const categoryList = ref([])
const selectedCategory = ref([])
const categoryTreeProps = {
  value: 'categoryId',
  label: 'categoryName',
  expandTrigger: 'hover'
}
const categoryId = ref(0)
const props = defineProps({
  isDistribution: {
    default: false,
    type: Boolean
  }
})

// 获取数据列表
const init = (id, discountProd) => {
  prodId.value = 0
  discountProds.value = discountProd
  clean()
  discountId.value = id
  visible.value = true
  dataListLoading.value = true
  if (discountProds.value) {
    discountProds.value.forEach(row => {
      dataListSelections.value.push(row)
    })
  }
  getDataList()
  getCategoryList()
}
const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      maxGrade: 2,
      status: 1
    })
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}
const showProd = (id, val) => {
  isShowProd.value = val
  discountId.value = id
  visible.value = true
  page.currentPage = 1
  http({
    url: http.adornUrl(`/admin/discountProd/info/${id}`),
    method: 'get',
    params: http.adornParams({
      current: page.currentPage,
      size: page.pageSize,
      prodType: 0,
      prodName: prodName.value || null,
      categoryId: categoryId.value || null
    })
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
  })
}
const showProdInit = (id, val) => {
  getCategoryList()
  showProd(id, val)
}

const prodTableRef = ref(null)
const getDataList = () => {
  http({
    url: http.adornUrl('/prod/prod/page'),
    method: 'get',
    params: http.adornParams({
      current: page.currentPage,
      size: page.pageSize,
      prodName: prodName.value || null,
      categoryId: categoryId.value || null,
      status: 1,
      isDistribution: props.isDistribution ? 1 : 0
    })
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
    dataListLoading.value = false
    nextTick(() => {
      if (discountProds.value) {
        discountProds.value.forEach(row => {
          const index = dataList.value.findIndex(prodItem => prodItem.prodId === row.prodId)
          prodTableRef.toggleRowSelection(dataList.value[index])
        })
      }
    })
  })
}
// 每页数
const onPageSizeChange = val => {
  page.pageSize = val
  page.currentPage = 1
  getDataList()
}
// 当前页
const onPageChange = val => {
  page.currentPage = val
  getDataList()
}
/**
 * 获取分类id
 */
const handleChange = val => {
  categoryId.value = val[val.length - 1]
}
/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  page.currentPage = 1
  if (props.isDistribution) {
    getDataList()
  } else {
    showProd(discountId.value, discountProds.value)
  }
}
/**
 * 清空搜索条件
 */
const clean = () => {
  prodName.value = ''
  categoryId.value = null
  selectedCategory.value = idList(
    categoryList.value,
    categoryId.value,
    'categoryId',
    'children'
  ).reverse()
}
// 选择产品
const selectProd = () => {
  if (isShowProd.value) {
    clean()
    visible.value = false
    return
  }
  const prods = []
  dataListSelections.value.forEach(item => {
    const prodIndex = prods.findIndex(prod => prod.prodId === item.prodId)
    if (prodIndex === -1) {
      prods.push({
        discountProdId: 0,
        prodId: item.prodId,
        prodName: item.prodName,
        pic: item.pic
      })
    }
  })
  emit('refreshDiscountProds', prods)
  dataListSelections.value = []
  visible.value = false
}
// 获取当选的行
// eslint-disable-next-line no-unused-vars
const getSelectProdRow = (index, row) => {
  dataListSelections.value = []
  dataListSelections.value.push(row)
}
// 关闭页面操作
const beforeClose = done => {
  clean()
  done()
}

defineExpose({
  init,
  showProdInit
})
</script>
<style lang="scss" scoped>
.main-container.distribution-prod-add-or-update {
  padding: 0;
  max-height: 480px;
  .table-con {
    padding-bottom: 20px;
  }
}
</style>
